package edu.pku.sei.transformation.atl.engine;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import edu.pku.sei.transformation.atl.codegen.ATLGenerator;
import edu.pku.sei.transformation.editor.model.ModelType;
import edu.pku.sei.transformation.editor.model.execution.Pin;
import edu.pku.sei.transformation.editor.model.execution.TransformationExecution;
import edu.pku.sei.transformation.editor.views.problem.ProblemView;
import edu.pku.sei.transformation.engine.EngineExtraData;
import edu.pku.sei.transformation.engine.IEngineAdapter;
import edu.pku.sei.transformation.engine.IEngineRunner;
import edu.pku.sei.transformation.execution.ExecutionEnviroment;

public class ATLAdapter implements IEngineAdapter {

	@Override
	public EngineExtraData getExtraData(EngineExtraData oringin) {
		return null;
	}

	@Override
	public String getID() {
		return "ATL Engine";
	}

	@Override
	public IEngineRunner getRunner(TransformationExecution execution,
			ExecutionEnviroment env) throws Exception {
		ATLRunner runner = new ATLRunner();
		for (Pin p : execution.getActualParameters()) {
			String modelName = p.getFormalParameter().getName();
			String metaModelName = "";
			String modelPath = env.getPath(p);
			String metaModelPath = "";
			
			if (modelName == null || modelName.equals("")) {
				ProblemView.addError(execution.getModel(), ProblemView.EXECUTION, "formal parameter", "parameter do not have a name", p.getFormalParameter().getName());
			}
			if (p.getFormalParameter().getType() instanceof ModelType) {
				metaModelName = ((ModelType)p.getFormalParameter().getType()).getMetaModel().getName();
				metaModelPath = ((ModelType)p.getFormalParameter().getType()).getMetaModel().getFilePath();
			} else {
				ProblemView.addError(execution.getModel(), ProblemView.EXECUTION, "formal parameter", "parameter type is not a meta-model", p.getFormalParameter().getName());
				throw new Exception("parameter type is not a meta-model: " + p.getFormalParameter().getName());
			}
			
			runner.registModel(modelName, modelPath, metaModelName, metaModelPath);
		}
		
		runner.setTargetModel(execution.getDirection().getName());
		
		ATLGenerator generator = new ATLGenerator();
		String rule = generator.generate(execution);
		
		File ruleFile = new File(execution.getWorkDir()+"\\temp\\" + execution.getTransformation().getName()
				+ ".atl").getAbsoluteFile();
		String rulePath = ruleFile.getAbsolutePath();
		FileWriter fw;
		try {
			fw = new FileWriter(ruleFile);
			fw.write(rule, 0, rule.length());
			fw.flush();
			fw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		runner.setRuleFile(rulePath);
		File asmFile = new File(execution.getWorkDir()+"\\temp\\" + execution.getTransformation().getName()
				+ ".asm").getAbsoluteFile();
		runner.setAsmPath(asmFile.getAbsolutePath());
		return runner;
	}

}
